package com.itheima.factory;




import com.itheima.utils.SqlSessionUtils;
import org.apache.ibatis.session.SqlSession;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class DaoInstanceFactory {
    public static <T> T getMapper(Class<T> interfaceClass){
        //1.获取sqlSession
        SqlSession sqlSession = SqlSessionUtils.getSqlsession();
        //2.使用框架生成代理对象
        T mapper = sqlSession.getMapper(interfaceClass);
        //3.对框架生成代理对象方法进行加强,让其支持事务
        T   proxy_mapper = (T) Proxy.newProxyInstance(mapper.getClass().getClassLoader(), new Class[]{interfaceClass}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                Object value = null;
                try {
                    //开启事务
                     value = method.invoke(mapper, args);
                    //成功:提交事务
                    sqlSession.commit();
                } catch (Exception e) {
                    //失败:回滚事务
                    sqlSession.rollback();
                    e.printStackTrace();
                } finally {
                    //最后释放资源
                    sqlSession.close();
                }
                return value;
            }
        });
        return proxy_mapper;
    }
}
